/*
 * ImageFilter.m, Image filter service example.
 * Author: Ali T. Ozer, NeXT Computer, Inc.
 * Written for 3.0, June 1, 1992.
 *
 * You may freely copy, distribute and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or implied, as to its
 * fitness for any particular use.
 */

#import	<appkit/appkit.h>

extern NXBitmapImageRep *convertIFFToTIFF (NXStream *imageStream);

@interface ImageConverter : Object
- convertToTIFF:pb userData:(const char *)userData error:(char **)errorMessage;
@end

@implementation ImageConverter

- convertToTIFF:pasteboard userData:(const char *)userData error:(char **)errorMessage
{
    static NXAtom typesThatCanBeConverted[2] = {NULL, NULL};
    NXAtom typeToBeConverted;
    char fileToBeConverted[MAXPATHLEN+1];
    NXStream *imageStream = NULL;

    if (!typesThatCanBeConverted[0]) {
	typesThatCanBeConverted[0] = NXCreateFilenamePboardType("iff");
	typesThatCanBeConverted[1] = NULL;
    }

    if (typeToBeConverted = [pasteboard findAvailableTypeFrom:typesThatCanBeConverted num:1]) {
	char *data, *separator, *extension;
	int dataLen;
	[pasteboard readType:typeToBeConverted data:&data length:&dataLen];
	if (data && dataLen) {
	    // Copy the name of the first file in the file list into "path"
	    // (Usually there will only be one file, but don't take any chances!)
	    int strLen = (separator = index(data, '\t')) ? (separator - data) : dataLen;
	    strncpy(fileToBeConverted, data, strLen);
	    fileToBeConverted[strLen] = 0;
	    // Make sure the file extension is what we want. If not, we punt.
	    extension = rindex(fileToBeConverted, '.');
	    if (extension && (strcmp(extension, ".iff") == 0)) {
		imageStream = NXMapFile(fileToBeConverted, NX_READONLY);
	    }
	}
	// Deallocate the file name list
	[pasteboard deallocatePasteboardData:data length:dataLen];
    }

    if (imageStream) {
	NXBitmapImageRep *tiffImage = nil;
	NXStream *tiffStream = NULL;
	NX_DURING
	    if (tiffImage = convertIFFToTIFF (imageStream)) {
		tiffStream = NXOpenMemory (NULL, 0, NX_READWRITE);
		[tiffImage writeTIFF:tiffStream];
		[pasteboard declareTypes:&NXTIFFPboardType num:1 owner:self];
		[pasteboard writeType:NXTIFFPboardType fromStream:tiffStream];
	    }
	NX_HANDLER
	    NXLogError ("Error occurred while converting file %s:", fileToBeConverted);
	    NXReportError(&NXLocalHandler);
	NX_ENDHANDLER
	if (tiffImage) [tiffImage free];
	if (tiffStream) NXCloseMemory (tiffStream, NX_FREEBUFFER);
	NXCloseMemory (imageStream, NX_FREEBUFFER);
	imageStream = NULL;
    }

    return self;
}

@end

int main(int argc, char **argv)
{
    id listener = [Listener new];
    [listener setServicesDelegate:[ImageConverter new]];
    [listener checkInAs:"A Simple Image Converter"];
    [listener addPort];
    [Listener run];
}

